package com.varian.security.authorization;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.varian.security.model.LoginUser;
import com.varian.security.util.SecurityUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

import java.util.Map;

/**
 * @author ben
 * @since 2024/6/23
 */
public class VarianJwtBearerTokenAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {

    private final JwtAuthenticationConverter jwtAuthenticationConverter;

    public VarianJwtBearerTokenAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        // 去掉SCOPE_前缀
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(StrUtil.EMPTY);
        converter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        this.jwtAuthenticationConverter = converter;
    }


    @Override
    public AbstractAuthenticationToken convert(Jwt jwt) {
        AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
        Map<String, Object> attributes = jwt.getClaims();
        Long userId = MapUtil.getLong(attributes, JWT.SUBJECT);
        LoginUser principal = SecurityUtil.getLoginUserByCache(userId);
        return new VarianJwtAuthenticationToken(jwt, principal, token.getCredentials(), principal.getAuthorities());
    }
}
